<!doctype html>


<html>
  <head>
    <meta charset="utf-8">
    <title>Emscripten:Export1</title>
  </head>
  <body>
  <script type="module">
        import YUVSurfaceShader from './YUVSurfaceShader.js'
        import Texture from './Texture.js'

        /**
         * @type {Array<Uint8Array>}
         */
        const h264samples = []

        /**
         * @param {Uint8Array}buffer
         * @param {number}width
         * @param {number}height
         */
        function onPicture (buffer, width, height) {
    
          this.canvas.width = width;
          this.canvas.height = height;
          const lumaSize = width * height;
          const chromaSize = lumaSize >> 2;
		  const yBuffer = buffer.subarray(0, lumaSize);
		  const uBuffer = buffer.subarray(lumaSize, lumaSize + chromaSize);
          const vBuffer = buffer.subarray(lumaSize + chromaSize, lumaSize + (2 * chromaSize));
		  const chromaHeight = height >> 1;
          const chromaStride = width >> 1;
          this.yTexture.image2dBuffer(yBuffer, width, height);
          this.uTexture.image2dBuffer(uBuffer, chromaStride, chromaHeight);
          this.vTexture.image2dBuffer(vBuffer, chromaStride, chromaHeight);

          this.yuvSurfaceShader.setTexture(this.yTexture, this.uTexture, this.vTexture);
          this.yuvSurfaceShader.updateShaderData({ w: width, h: height },
		  { maxXTexCoord:1,maxYTexCoord:1 });
          this.yuvSurfaceShader.draw();
        }

        function initWebGLCanvas (index) {
          canvas = document.createElement('canvas')
          const gl = canvas.getContext('webgl')
          yuvSurfaceShader = YUVSurfaceShader.create(gl)
          yTexture = Texture.create(gl, gl.LUMINANCE)
          uTexture = Texture.create(gl, gl.LUMINANCE)
          vTexture = Texture.create(gl, gl.LUMINANCE)

          document.body.append(canvas);
        }
        function initScreen (num) {
		  let screens = [];
		  for(let i=0;i<num;i++){
			let screen = {};
			  screen.canvas = document.createElement('canvas');
			  screen.gl = screen.canvas.getContext('webgl');
			  screen.onPicture = onPicture;
			  screen.yuvSurfaceShader = YUVSurfaceShader.create(screen.gl);
              screen.yTexture = Texture.create(screen.gl, screen.gl.LUMINANCE);
			  screen.uTexture = Texture.create(screen.gl, screen.gl.LUMINANCE);
              screen.vTexture = Texture.create(screen.gl, screen.gl.LUMINANCE);
			  screens.push(screen);
			  document.body.append(screen.canvas);
		  }
		  return screens;
        }
        window.screens = initScreen(4)
    </script>  
   <script type="text/javascript">
    Module = {};
	window.worker1 = new Worker("txdemux2.js");
	window.worker1.onmessage = function (evt) {//640*360
		window.screens[0].onPicture(new Uint8Array(evt.data),1920,1080);
	};
	window.worker2 = new Worker("txdemux2.js");
	window.worker2.onmessage = function (evt) {//640*360
		window.screens[1].onPicture(new Uint8Array(evt.data),640,360);
	};
	window.worker3 = new Worker("txdemux2.js");
	window.worker4 = new Worker("txdemux2.js");
    // var ws = new WebSocket("wss://echo.websocket.org");
    /*
    ws.onerror = function(e) {
      console.log('已关闭');
    };
    ws.onopen = function(e) {
      console.log('握手成功');
      ws.send('123456789');
    }
    ws.onclose = function() {
      console.log('已关闭');
    }
    ws.onmessage = function(e) {
      console.log('收到消息');
      console.log(e);
    }
    */
    
	
	var demuxBuffer = null;
    var lockReconnect = false;//避免重复连接
    var wsUrl = "ws://127.0.0.1:28802";
    var ws;
    var tt;
    function createWebSocket() {
      try {
        ws = new WebSocket(wsUrl);
        init();
      } catch(e) {
        console.log('catch');
        reconnect(wsUrl);
      }
    }
    function init() {
      ws.onclose = function () {
        console.log('链接关闭');
        reconnect(wsUrl);
      };
      ws.onerror = function() {
        console.log('发生异常了');
        reconnect(wsUrl);
      };
      ws.onopen = function () {
        //心跳检测重置
        ws.send("RTMP_OPEN:192.168.0.254");
      };
      ws.onmessage = function (event) {
        //拿到任何消息都说明当前连接是正常的
		    let reader = new FileReader();
            reader.onload = () => {
				let u8Array = new Uint8Array(reader.result);
				const sliced = reader.result.slice(1);
				switch(u8Array[0]){
					case 0:worker1.postMessage(sliced, [sliced]);break;
					case 1:worker2.postMessage(sliced, [sliced]);break;
					case 2:worker3.postMessage(sliced, [sliced]);break;
					case 3:worker4.postMessage(sliced, [sliced]);break;
				}
            };
        reader.readAsArrayBuffer(event.data);
        //console.log('接收到消息');
        //heartCheck.start();
		
      }
    }
    function reconnect(url) {
      if(lockReconnect) {
        return;
      };
      lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      tt && clearTimeout(tt);
      tt = setTimeout(function () {
        createWebSocket(url);
        lockReconnect = false;
      }, 4000);
    }
    //心跳检测
    var heartCheck = {
      timeout: 3000,
      timeoutObj: null,
      serverTimeoutObj: null,
      start: function(){
        //console.log('start');
        var self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function(){
          //这里发送一个心跳，后端收到后，返回一个心跳消息，
          //console.log('55555');
          self.serverTimeoutObj = setTimeout(function() {
            //console.log(111);
            //console.log(ws);
            ws.close();
            // createWebSocket();
          }, self.timeout);
 
        }, this.timeout)
      }
    }
    createWebSocket(wsUrl);
  </script>
  </body>
</html>